package site.suremotoo.demo.delaypay.consumer;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import site.suremotoo.demo.delaypay.config.QueueConstant;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author liulx
 * @description TODO
 * @date 2020-12-28 20:58
 */
@Component
public class MqConsumer {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(queues = QueueConstant.ORDER_QUEUE_NAME)
    public void orderConsumer(Message message, Channel channel) throws IOException {
        String data = new String(message.getBody(), StandardCharsets.UTF_8);
        System.out.println("消费者从：" + QueueConstant.ORDER_QUEUE_NAME + " 队列中，消费了消息：" + data);
        System.out.println();
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        System.out.println("下单成功，等待支付中...");
        System.out.println();
    }

    public void payConsumer() throws IOException {
        Object o = rabbitTemplate.receiveAndConvert(QueueConstant.PAY_QUEUE_NAME);
        System.out.println("消费者从：" + QueueConstant.PAY_QUEUE_NAME + " 队列中，消费了消息：" + o);
        System.out.println("支付成功...");
        System.out.println();
    }


    @RabbitListener(queues = QueueConstant.DLX_QUEUE_NAME)
    public void dlxConsumer(Message message, Channel channel) throws IOException {
        System.out.println();
        System.out.println("支付超时，订单自动关闭...");
        String data = new String(message.getBody(), StandardCharsets.UTF_8);
        System.out.println("消费者从：" + QueueConstant.DLX_QUEUE_NAME + " 队列中，消费了消息：" + data);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        System.out.println("模拟用户历史账单中查看因付款超时而取消的订单，取消的订单信息：" + data);
        System.out.println();
    }

}
